package dongshi.daddy.springioc.three.three_five.config;

import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class AppConfig {

    /**
     * database.driverName=com.mysql.jdbc.Driver
     * database.url=jdbc:mysql://localhost:3306:chapter3
     * database.username=root
     * database.password=123456
     * @return
     */
    @Bean(name = "dataSource", destroyMethod = "close")
    @Conditional(DatabaseCondition.class)
    public DataSource getDataSource(
            @Value("database.driverName") String driverName,
            @Value("database.url") String url,
            @Value("database.username") String username,
            @Value("database.password") String password
    ) {
        Properties properties = new Properties();
        properties.setProperty("driver", driverName);
        properties.setProperty("url", url);
        properties.setProperty("username", username);
        properties.setProperty("password", password);
        DataSource dataSource = null;
        try {
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSource;
    }
}
